package com.hysoft.cxf.ws.auth.header;


import java.util.List;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

//通过PhaseInterceptor,可以指定拦截器在那个阶段起作用.
public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage>  {

	public AuthInterceptor() {
		super(Phase.PRE_INVOKE);//调用之前拦截soap消息
	}

	//实现自己的拦截器时,需要实现handleMessage方法.
	//handleMessage方法中的形参就是被拦截的Soap消息.
	//一旦程序获取了Soap消息,剩下的事情就可以解析soap消息,或修改soap消息
	@Override
	public void handleMessage(SoapMessage msg) throws Fault {
		System.out.println("-----------------" + msg);
		
		//得到soap消息的所有header
		List<Header> headers = msg.getHeaders();
		if (headers == null || headers.size() < 1) {
			throw new Fault(new IllegalArgumentException("没有Header"));
		}
		
		Header firstHeader = headers.get(0);
		Element ele = (Element) firstHeader.getObject();
		
		NodeList userIds = ele.getElementsByTagName("userId");
		NodeList pwds = ele.getElementsByTagName("password");
		
		if (userIds.getLength() != 1) {
			throw new Fault(new IllegalArgumentException("用户名格式不对"));
		}
		if (pwds.getLength() != 1) {
			throw new Fault(new IllegalArgumentException("密码格式不对"));
		}
		
		String userId = userIds.item(0).getTextContent();
		String pwd = pwds.item(0).getTextContent();
		
		if (!"wz".equals(userId) || !"1234".equals(pwd)) {
			throw new Fault(new IllegalArgumentException("用户名,密码错误"));
		}
		
	}

}
